<?php

namespace backend\components;

use backend\server\RoleServer;
use common\logic\MenuLogic;
use common\logic\RoleLogic;
use common\models\AuthRuleModel;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/19
 * Time: 下午11:31
 */

class MenuHelper
{

    /**
     * 放行路由
     * @var array
     */
    public static $allowUrl = [
        'site/logout',
        'site/login',
        'index/index',
    ];

    /**
     * @var AuthRuleModel[]
     */
    protected static $menus;


    protected static function getMenu($role_id)
    {
        $ids = [];
        if ($role_id != RoleServer::ROLE_SUPER) {
            $role =   RoleLogic::instance()->getById($role_id);
            $ids = explode(',',$role->rule);
			
            if(empty($ids)){
                return [];
            }
        }
        if (empty(self::$menus)) {
            $menus = MenuLogic::instance()->getAll($ids);
            self::$menus = $menus;
        }
		
		
		
        return self::$menus;
    }

    /**
     * 获取菜单
     *
     * @param $role_id
     * @return array|AuthMenuModel[]
     */
    public static function getAssignedMenu($role_id)
    {

        $menus = self::getMenu($role_id);

        $menus = array_filter($menus,function($menu){
            return $menu->is_show > 0;
        });

        $menus = self::formatMenus($menus, 0);
        return $menus;
    }

    /**
     * @param AuthRuleModel[] $menus
     * @param int $parent_id
     * @return array
     */
    protected static function formatMenus($menus, $parent_id = 0)
    {
        $items = [];
        foreach ($menus as $key => $menu) {
            if ($menu->pid == $parent_id) {
                $item = ['label' => $menu->title, 'icon' => $menu->icon, 'url' => static::parseRoute($menu->route)];
                unset($menus[$key]);
                $child = self::formatMenus($menus, $menu->id);
                if (!empty($child)) {
                    $item['items'] = $child;
                }
                $items[] = $item;
            }
        }
        return $items;
    }

    /**
     * Parse route
     * @param  string $route
     * @return mixed
     */
    public static function parseRoute($route)
    {
        if (!empty($route)) {
            $url = [];
            $r = explode('&', $route);
            $url[0] = $r[0];
            unset($r[0]);
            foreach ($r as $part) {
                $part = explode('=', $part);
                $url[$part[0]] = isset($part[1]) ? $part[1] : '';
            }

            return $url;
        }

        return '#';
    }

    public static function normalizeRoute($route)
    {
        if ($route === '') {
            return '/' . Yii::$app->controller->getRoute();
        } elseif (strncmp($route, '/', 1) === 0) {
            return $route;
        } elseif (strpos($route, '/') === false) {
            return '/' . Yii::$app->controller->getUniqueId() . '/' . $route;
        } elseif (($mid = Yii::$app->controller->module->getUniqueId()) !== '') {
            return '/' . $mid . '/' . $route;
        }
        return '/' . $route;
    }

    /**
     * Check access route for user.
     * @param string|array $route
     * @return boolean
     */
    public static function checkRoute($route)
    {
        $allowUrl = array_merge(Yii::$app->params['allowUrl'], self::$allowUrl);
        $route = static::normalizeRoute($route);
        /** @var \common\models\AdminModel $user */
        $user = Yii::$app->user->getIdentity();
        if($user->role_id == RoleServer::ROLE_SUPER) return true;
        $rules = self::getMenu($user->role_id);
        $rules = ArrayHelper::map($rules, 'id', 'route');
        $rules = array_merge($rules, $allowUrl);
        return in_array($route, $rules);
    }

    public static function filterActionColumn($buttons = [], $user = null)
    {
        if (is_array($buttons)) {
            $result = [];
            foreach ($buttons as $button) {
                if (static::checkRoute($button, [], $user)) {
                    $result[] = "{{$button}}";
                }
            }
            return implode(' ', $result);
        }
        return preg_replace_callback('/\\{([\w\-\/]+)\\}/', function ($matches) use ($user) {
            return static::checkRoute($matches[1], [], $user) ? "{{$matches[1]}}" : '';
        }, $buttons);
    }
}